package org.hk.kg.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hk.kg.KGMain;
import org.hk.kg.TraceObject;
import org.hk.kg.utils.Constants;
import org.hk.kg.utils.LocalResouce;
import org.hk.kg.utils.StringUtils;
import org.hk.kg.utils.XMLUtils;
import org.hk.kg.web.BaseAction;
import org.jdom.Document;
import org.jdom.Element;

public class KGUiContext {
	private static KGFrame displayMain;
	
	private IStatus status;
	
	public static KGUiContext instance = new KGUiContext();
	
	private static Map<String,BaseAction> action_stack = new HashMap<String,BaseAction>();
	
	private TraceObject trace;
	
	/** 当前跳转页是否被记录进历史 */
	private boolean didTrace;
	
	private static Log logger = LogFactory.getLog(KGUiContext.class);
	
	public KGUiContext()
	{
		//trace = new ArrayList<TraceObject>();
	}

	/**
	 * @param object
	 */
	private void traceAppend(TraceObject object)
	{
		if(trace != null)
		{
			object.setPrev(trace);
			trace.setNext(object);
		}
		trace = object;
		didTrace = true;
	}
	
	public TraceObject action_backward()
	{
		TraceObject rlt = trace.getPrev();
		action_stack.get(rlt.getCommandId()).request();
		trace = rlt;
		return rlt;
	}	
	
	public void action(TraceObject trace)
	{
		if(displayMain!=null)
		{
			BaseAction action = action_stack.get(trace.getCommandId());
			if(action != null)
			{
				action.request(trace.getParams());
			}
			else
			{
				String msg = String.format(Constants.MSG_COMMON_PAGE_NULL, trace.getCommandId());
				KGUiContext.instance.setStatusTxt(msg);
				logger.error(msg);
			}
			if(trace.isTaceable() && this.trace != trace)
			{
				traceAppend(trace);
			}
		}
	}
	
	public void error(String errorTitle,String errorMsg)
	{
		JOptionPane.showMessageDialog(this.displayMain,
				errorMsg, errorTitle,
				JOptionPane.ERROR_MESSAGE);
	}
	
	public void setStatusTxt(String txt)
	{
		if(this.status != null)
		{
			this.status.setStatusText(txt);
		}
	}
	
	public	 String currentUsr()
	{
		return "testUsr_v1.0";
	}
	
	protected static void setDisplayMain(KGFrame displayMain) {
		KGUiContext.displayMain = displayMain;
	}

	public static void setStatus(IStatus status) {
		KGUiContext.instance.status = status;
	}	
	
	public static Map<String, BaseAction> getActionStack() {
		return action_stack;
	}
	
	public static void addAction(String id,String packageName,String action)
	{
		if(packageName == null)
		{
			packageName = "";
		}
		if(!action_stack.containsKey(id))
		{
			try {
				Class<?> actionClz = ClassLoader.getSystemClassLoader().loadClass(action);
				if(BaseAction.class.isAssignableFrom(actionClz))
				{
					BaseAction actionObj = (BaseAction) actionClz.newInstance();
					actionObj.setDisplayer(displayMain.displayer);
					actionObj.setId(id);
					actionObj.setPackage(packageName);
					action_stack.put(id, actionObj);
					logger.debug(String.format("regist %s[%s]",id,action));
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void addAction(String action,String packageName)
	{
		addAction(action,packageName,action);
	}

	public static String current()
	{
		if(instance.trace == null)
		{
			return "";
		}
		return instance.trace.getCommandId();
	}
	
	public void load()
	{
		InputStream ui_xml_ips = null;
		Document document = null;
		try {
			ui_xml_ips = LocalResouce.getConfigFile(Constants.UI_CONFIG);
			document = XMLUtils.getDocument(ui_xml_ips);
		} catch (Exception e) {
			logger.error(e);
		}
		Element global_ele = XMLUtils.getElementFromDoc(document, Constants.UI_CONFIG_ACTIONS_TAG);
		for(Object itemTemp : global_ele.getChildren())
		{
			Element item = (Element) itemTemp;
			String id = item.getAttributeValue(Constants.UI_CONFIG_ACTION_ID),
				pack = item.getAttributeValue(Constants.UI_CONFIG_ACTION_PACKAGE),
				action = item.getAttributeValue(Constants.UI_CONFIG_CLASS_ATTR);
			if(!StringUtils.isEmpty(id))
			{
				if(!StringUtils.isEmpty(action))
				{
					KGUiContext.addAction(id,pack,action);
				}
				else
				{
					KGUiContext.addAction(id,pack,"org.hk.kg.web.BaseAction");
				}
			}
		}
		
		Element task_ele = XMLUtils.getElementFromDoc(document, Constants.UI_CONFIG_TASKS_TAG);
		for(Object itemTemp : task_ele.getChildren())
		{
			Element item = (Element) itemTemp;
			try {
				Class<?> task = this.getClass().getClassLoader().loadClass(item.getAttributeValue(Constants.UI_CONFIG_CLASS_ATTR));
				KGMain.tasks.add((Runnable) task.newInstance());
			} catch (ClassNotFoundException e) {
				logger.error(e);
			} catch (InstantiationException e) {
				logger.error(e);
			} catch (IllegalAccessException e) {
				logger.error(e);
			}
		}
	}
}

